from myapp import models
from myapp.utils.Pagination import Pagination
from django.shortcuts import render,redirect
from myapp.utils.form import AdminModeForm, AdminUpdateModelForm, AdminResetModeForm


def admin_list(request):
    """管理员列表"""

    #  搜索功能
    serach_dict = {}
    search_data = request.GET.get('search_data','')
    if search_data:
        serach_dict['username__contains'] = search_data
    datalist = models.Admin.objects.filter(**serach_dict)
    # 分页
    pageobj = Pagination(request,query_set=datalist)
    data_set = pageobj.data_queryset
    page_str = pageobj.html()
    data_dict = {
        'data_set':pageobj.data_queryset,
        'page_str':pageobj.html(),
        'search_data':serach_dict
    }
    return render(request,'admin_list.html',data_dict)

def admin_add(request):
    """管理员添加"""
    if request.method =="GET":
        form = AdminModeForm()
        return render(request, 'change.html', {'form':form})
    form = AdminModeForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form':form, 'title': '管理员添加'})

def admin_update(request,nid):
    """更新管理员账号"""
    row_obj = models.Admin.objects.filter(id=nid).first()
    if request.method == "GET":
        form = AdminUpdateModelForm(instance=row_obj)
        if not row_obj:
                return render(request,'error.html',{'msg':'数据不存在'})
        return render(request, 'change.html', {"form": form,"title":"账户更新"})
    form = AdminUpdateModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request,'change.html',{"form":form,"title":"账户更新"})

def admin_delete(request,nid):
    """删除管理员"""
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')

def admin_reset(request,nid):
    """重置密码"""
    row_obj = models.Admin.objects.filter(id=nid).first()
    title = '重置密码----{}'.format(row_obj.username)
    if request.method =="GET":
         form = AdminResetModeForm(instance=row_obj)
         return render(request,'change.html',{'form':form,"title":title})
    form = AdminResetModeForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')

    return render(request, 'change.html', {'form': form, "title": title})


